<?php
/**
 * 
 * Lop xl voi table kiemtra (tao bai trac nghiem)
 * @author Vo Xuan Hoan
 *
 */
class Admin_QuizController extends ExtLb_Controller_Action{

	private $testQuestion;	//danh sach cac cau hoi cua 1 bai kiem tra
	private $exame;		//danh sach cac bai kiem tra
	private $question; 	//danh sach cac cau hoi
	private $lopKiemTra; // obj cua lop-kiemtra
	private $mon;
	private $manager; /// obj cua quanly
	private $quizSessionSet;
	private $quizSessionGet;
	
	private $exameForm;
	private $authLogin;
	
    public function init(){
        $this->loadLayout('admin', 'layout');
        $this->loadCss('admin', 'quiz');
        $this->loadCssPath('/public/css/multiselect/jquery.multiselect.css');
        $this->loadCssPath('/public/css/multiselect/jquery.multiselect.filter.css');
        $this->loadCssPath('/public/css/multiselect/style.css');
        $this->loadCssPath('/public/css/multiselect/prettify.css');
        
        $this->testQuestion = new Admin_Model_Kiemtracauhoi();
        $this->exame 		= new Admin_Model_Kiemtra();
        $this->question 	= new Admin_Model_Question();
        $this->mon 			= new Admin_Model_Monhoc();
        $this->lopKiemTra 	= new Admin_Model_LopKiemTra();
        $this->manager		= new Admin_Model_Manages();
        $this->exameForm	= new Admin_Form_QuizForm();
        
        //
        // === Auth
        $this->authLogin	= Zend_Auth::getInstance()->getIdentity();
        
        //SESSION
        $this->quizSessionSet = new Zend_Session_Namespace('quizSession');
        
		//                               
        // === Set timezone
        date_default_timezone_set('Asia/Ho_Chi_Minh');
    }

    public function indexAction()
    {
    	//LOAD MON HOC DE FILTER
    	$monHoc = $this->mon->fetchAllMonHoc();

   		// === Xac dinh quyen han khi load
   		if ($this->authLogin->quyen != "admin"){
   			if(isset($_GET['tbn_filter']) && !empty($_GET['tbn_cate'])){
				$selectExame = $this->exame->selectManager_lopKiemTra("username = '{$this->authLogin->username}' and ql.idMonHoc = ".$_GET['tbn_cate']);	
				$_REQUEST['cbbMon']	= $_GET['tbn_cate'];
   			}else{
   				$selectExame = $this->exame->selectManager_lopKiemTra("username ='{$this->authLogin->username}'");	
   			}
   			
   			// === TIM kiem
   			if(isset($_GET['search_box_sumit']) && !empty($_GET['search_box_text'])){
    			$where = "username = '{$this->authLogin->username}' and ten like '%".$_GET['search_box_text']."%'";
				$selectExame = $this->exame->selectManager_lopKiemTra($where);
	    	}
   		}else{
   			// === Filter
   			if(isset($_GET['tbn_filter']) && !empty($_GET['tbn_cate'])){
				$selectExame = $this->exame->selectManager_lopKiemTra("ql.idMonHoc = ".$_GET['tbn_cate']);	
				$_REQUEST['cbbMon']	= $_GET['tbn_cate'];
   			}else{
   				$selectExame = $this->exame->selectManager_lopKiemTra();	
   			}
   			
   			// 	=== TIM kiem
	   		if(isset($_GET['search_box_sumit']) && !empty($_GET['search_box_text'])){
	    		if ($this->authLogin->quyen != "admin"){
	    			$where = "username = '{$this->authLogin->username}' and ten like '%".$_GET['search_box_text']."%'";
	    		}else{
	    			$where = "ten like '%".$_GET['search_box_text']."%'";
	    		}
				$selectExame = $this->exame->selectManager_lopKiemTra($where);
	    	}
    	}
    	
        $paginatorExame = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($selectExame));
        $paginatorExame->setItemCountPerPage(20)
        				->setPageRange(3)
        				->setCurrentPageNumber($this->_getParam('page'),1);
        				
        $this->view->paginatorExame = $paginatorExame;
        $this->view->monHoc = $monHoc;
    }

    public function addAction()
    {
        //XU LY THEM 1 BAI KIEM TRA MOI
        if(isset($_POST['cmdAdd'])){
        	try {
        		$name 			= ucfirst($this->_getParam('txtName'));
	        	$time 			= $this->_getParam('txtTime');
	        	$numQuestion 	= $this->_getParam('txtTotalNumQuestion');
	        	$dateStart		= $this->_getParam('txtDateStartD');
	        	$hourStart 		= $this->_getParam('txtDateStartH');
	        	$dateEnd 		= $this->_getParam('txtDateEndD');
	        	$hourEnd 		= $this->_getParam('txtDateEndH');
	        	$idMonHoc 		= $this->_getParam('cbbMon');
	        	$heSo	 		= $this->_getParam('cbbHeSo');
	        	$hocKy			= $this->_getParam('cbbHocKy');
	        	$now 			= getdate();
	        	$namHoc			= $now['year'];
	        	$idLop			= $this->_getParam('cbbLop'); // Lay ma lop de bo xung bao table lop-kiemtra

	        	//
	        	// ==== Them bai kiem tra truoc
	        	$this->exame->addKiemTra($name, $time, $numQuestion, $dateStart, $hourStart, $dateEnd, $hourEnd, $idMonHoc,$heSo,$hocKy,$namHoc);
	        	
	        	//
	        	// === Lay id bai kiem tra vua them
	        	$idQuizLastest = $this->exame->getMaxIdExame();
	        	
	        	//
	        	// === Bổ thêm vào bảng lớp với lớp được fep làm bài và id bài vừ tạo
        		for ($i=0;$i<count($idLop);$i++){
	        		$this->lopKiemTra->add($idLop[$i], $idQuizLastest);
	        	}
	        	
	        	$this->jDialogMessage("Thông báo","Thành công!!!");
        		
        	} catch (Exception $e) {
        		$this->jDialogMessage('Thông báo','Đã có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!!');
        	}

        	$this->_forward('addquestion','quiz','admin');
        }
        
        //GET DATA TO EDIT  EXAME LIST
        if(isset($_GET['editlist']) && !empty($_GET['id'])){
        	$this->exameForm->addSubmitButton('cmdEdit', 'Cập nhập');
        	$this->exameForm->addAction('edit');
        	
        	// get data to edit
        	$exame = $this->exame->fetchKiemTra($_GET['id']);
        	
        	$this->exameForm->addHiddenId('txtId',$exame['idKiemTra']);
        	
        	$this->exameForm->getElement('txtName')->setValue($exame['ten']);
        	$this->exameForm->getElement('txtTime')->setValue($exame['thoiGian']);
        	$this->exameForm->getElement('txtTotalNumQuestion')->setValue($exame['soCauHoi']);
        	$this->exameForm->getElement('txtDateStartD')->setValue($exame['dateStart']);
        	$this->exameForm->getElement('txtDateStartH')->setValue($exame['hourStart']);
        	$this->exameForm->getElement('txtDateEndD')->setValue($exame['dateEnd']);
        	$this->exameForm->getElement('txtDateEndH')->setValue($exame['hourEnd']);
        	$this->exameForm->getElement('cbbMon')->setValue($exame['idMonHoc']);
        	$this->exameForm->getElement('cbbHocKy')->setValue($exame['hocKy']);
        	$this->exameForm->getElement('cbbHeSo')->setValue($exame['heSo']);
//        	$this->exameForm->getElement('cbbLop')->setValue($_GET['idlop'])->setAttrib('selected', 'selected');
        }else{
        	$this->exameForm->addSubmitButton('cmdAdd', 'Thêm');
        	$this->exameForm->addAction('add');
        }
        
        $this->view->quizForm = $this->exameForm;
        
    }

    public function addquestionAction(){
		//SESSION
		$this->quizSessionGet = Zend_Session::namespaceGet('quizSession');
		
		//mon hoc
    	//khi chon nut xem cac cau hoi khi chon mon
    	if(isset($_POST['cmdViewMon']) || !empty($this->quizSessionGet)){
    		
    		$idMon = isset($_POST['cbbMon']) ? $_POST['cbbMon'] : $this->quizSessionGet['idMon'] ;
    		$selectQuestion = $this->question->listQuestion('idMonHoc = '.$idMon);

    		//SET SESION
    		$this->quizSessionSet->idMon = $idMon;
			$this->refreshSession('quizSession');
    		$_REQUEST['cbbMon'] = $idMon;

    		//
    		//XOA BO SESSION 
    		//bo session idKiemTra if chon mon kh�c
    		if(isset($_POST['cbbMon']) && $this->quizSessionGet['idMon'] != $_POST['cbbMon']){
    			unset($this->quizSessionSet->idKiemTra);
    		}
    		
    	}else{
    		$selectQuestion = $this->question->listQuestion('idMonHoc = 1');	
    	}
    	
    	//
    	//SAU KHI CHON MON MOI HIEN THI DANH SACH CAC BAI KIEM TRA CUA MON DO
    	if(!empty($this->quizSessionGet['idMon'])){
	    	
    		$selectListExame = $this->exame->listKiemTra('idMonHoc = '.$this->quizSessionGet['idMon']);
    		
    		//
    		// === Phan trang cho danh sach cac bai exame (bai kiem tra da tao
	    	$paginatorListExame = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($selectListExame));
	    	$paginatorListExame->setItemCountPerPage(20)
	    					->setPageRange(3)
    						->setCurrentPageNumber($this->_getParam('pagee',1));
    		
    		$this->view->paginatorListExame 	= $paginatorListExame; 
    					
    	}
    	//
    	// xem chi tiet cac cau hoi cua 1 exame
    	if(isset($_POST['cmdChoose']) && !empty($_POST['cb_listQuiz']) ||
    		!empty($this->quizSessionGet['idKiemTra'])){

    		$idKiemTra = isset($_POST['cb_listQuiz']) ? $_POST['cb_listQuiz'][0] : $this->quizSessionGet['idKiemTra'];
    		
    		
    		$selectExame = $this->testQuestion->listTestQuestion('kt.idKiemTra = '.$idKiemTra);
    		$exameName = $selectExame->query()->fetch();
    		
    		if(empty($exameName)){
    			$exameName = $this->exame->fetchKiemTra($idKiemTra);	
    		}
    		
    		// === SESSION
			$this->quizSessionSet->idKiemTra = $exameName['idKiemTra'];     		

			// === Phan trang
	    	// === Phan trang cho so cau hoi trong 1 bai Exame
	    	$paginatorExame = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($selectExame));
	    	$paginatorExame->setItemCountPerPage(20)
	    					->setPageRange(3)
	    					->setCurrentPageNumber($this->_getParam('page',1));
	    	
	    	$this->view->exameName = $exameName['ten'] ;
	    	$this->view->paginatorExame 	= $paginatorExame;
	    	
	    	$this->refreshSession('quizSession');
    	}
    	
    	try {
	    	//
	    	// === THEM CAC CAU HOI VAO BAI TEST
	    	if(isset($_POST['btAddToQuiz']) && !empty($_POST['cb_listQuestion'])){
	    		$arrQuestion = $_POST['cb_listQuestion'];
	    		
	    		for($i=0; $i< count($arrQuestion); $i++){
	    			$this->testQuestion->addTestQuestion($arrQuestion[$i], $this->quizSessionGet['idKiemTra']);	
	    		}
	    	}
	    	
    	} catch (Exception $e) {
    		$this->jDialogMessage("Thông báo","Lỗi xử lý!!! Có thể câu hỏi này bạn đã có trong bài test. Kiểm tra lại!!!");
    	}
    	
    	
    	//phan trang
		//phan trang cho list cac cau hoi
		$paginatorListQuestion = new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($selectQuestion));
		$paginatorListQuestion->setItemCountPerPage(20)
							->setPageRange(3)
							->setCurrentPageNumber($this->_getParam('pageq',1));
    			
    	$this->view->listMonHoc = $this->mon->fetchAllMonHoc();
    	$this->view->paginatorListQuestion 	= $paginatorListQuestion;
    	
    	//CHUYEN SANG CONTROLLER KHAC
    	if(isset($_POST['cmdAddQues'])){
    		$this->_redirect('/admin/question/');
    	}
    	if(isset($_POST['cmdDelQues'])){
    		$this->_forward('delete','question','admin');
    	} 
    	if(isset($_POST['cmdAddQuiz'])){ 
    		$this->_redirect('admin/quiz/add'); 
    	}
    }

    public function editAction()
    {
        if($this->exameForm->isValid($this->_request->getPost())){
        	
        	if(isset($_POST['cmdEdit'])){
        		$name 			= $this->_getParam('txtName');
	        	$time 			= $this->_getParam('txtTime');
	        	$numQuestion 	= $this->_getParam('txtTotalNumQuestion');
	        	$dateStart		= $this->_getParam('txtDateStartD');
	        	$hourStart 		= $this->_getParam('txtDateStartH');
	        	$dateEnd 		= $this->_getParam('txtDateEndD');
	        	$hourEnd 		= $this->_getParam('txtDateEndH');
	        	$idMonHoc 		= $this->_getParam('cbbMon');
	        	$idKiemTra		= $this->_getParam('txtId');
	        	$hocKy			= $this->_getParam('cbbHocKy');
	        	$idLop			= $this->_getParam('cbbLop');
	        	$now 			= getdate();
        		$namHoc			= $now['year'];
	        	
        		try {
        			$this->exame->updateKiemTra($name, $time, 
	        					$numQuestion, $dateStart, 
	        					$hourStart, $dateEnd, 
	        					$hourEnd,$hocKy,$namHoc, 
	        					$idMonHoc,$idKiemTra
	        				);
	        		
	        		//
		        	// === Bổ thêm vào bảng lớp với lớp được fep làm bài và id bài vừ tạo
	        		for ($i=0;$i<count($idLop);$i++){
		        		$this->lopKiemTra->update(array('idLop' => $idLop[$i]), 'idKiemTra ='.$idKiemTra);
		        	}
		        	
	        		
	        	
	        		// 
		        	// === Cap nhap lai table quanly voi bai kiem tra, nguoi tao, mon dc phep lam
//		        	$this->manager->update(array(
//		        							'idLop' 	=>$idLop,
//		        							'idMonHoc' 	=> $idMonHoc
//		        						),
//		        						"username'".$this->authLogin->username."'"  
//	        								
//	        					);
	        		$this->jDialogMessage('Thông báo','Thành công!!!');	
        		} catch (Exception $e) {
        			$this->jDialogMessage('Thông báo','Đã có lỗi xảy ra trong quá trình xử lý. Hãy thử lại!!!');
        		}
	        	
	        	$this->_forward('addquestion','quiz','admin');
        	}else{
    			$this->_redirect('admin/quiz/add/?edit&id='.$_POST['txtId']);
        	}
        }else{
        	$this->_redirect('admin/quiz/add/?edit&id='.$_GET['id']);
        }
        
    }

    public function deleteAction()
    {
    	$this->refreshSession('quizSession');
    	//
    	// === Xoa bai kiem tra da tao của lớp (chỉ xóa bài của lớp);
    	if (!empty($_GET['id']) && isset($_GET['deletelist']) && isset($_GET['idlop']) && !empty($_GET['idlop'])) {
    		
    		
    		//
    		// === Kiem tra xem if cac lop lam bai kiem tra ko con 
    		// === hoac chi = 1 
    		// === thi se xoa lun bai kiem tra da tao cho cac lop
    		if(count($this->lopKiemTra->fetchAll("idKiemTra = 10"))>1){
    			
    			// === Xoa trong bang lop-kiemtra
    			$this->lopKiemTra->delete("idKiemTra =".$_GET['id']." and idLop ='".$_GET['idlop']."'");	
    		}else{
    			
    			$this->exame->deleteKiemTra($_GET['id']);
    			$this->lopKiemTra->delete("idKiemTra =".$_GET['id']." and idLop ='".$_GET['idlop']."'");	
    		}
    		
    		$this->jDialogMessage('Thông báo','Đã xóa!!!');
    		$this->_forward('index','quiz','admin');
    	}
    	
    	if(isset($_GET['deleteexame']) && !empty($_GET['id'])){
    		$this->testQuestion->deleteRowQuestion($_GET['id'],$this->quizSessionGet['idKiemTra']);
    		
    		$this->jDialogMessage('Thông báo','Đã xóa!!!');
    		$this->_forward('addquestion','quiz','admin');
    	}
    	
    	if(isset($_POST['cmdDelQuestionInExame']) && !empty($_POST['cbChooseQuiz'])){
    		$arrDel = $_POST['cbChooseQuiz'];
    		for($i=0; $i<count($arrDel); $i++){
    			$this->testQuestion->deleteRowQuestion($arrDel[$i], $this->quizSessionGet['idKiemTra']);
    		}
    		
    		$this->_redirect('admin/quiz/addquestion');
    	}
    	
    	//$this->_redirect('admin/quiz/addquestion');
    }

    public function doexameAction(){
    	if(isset($_GET['exe']) && !empty($_GET['id'])){
    		$check  = $this->exame->fetchKiemTra($_GET['id']);

    		//CHECK DATE TO ALLOW CONTINUE DO EXAME
    		$nows = getdate();
    		$hourMinute = explode("h", $check['hourEnd']);
    		$dateEnd	= explode("/", $check['dateEnd']);

    		$now	= mktime($nows['hours'],$nows['minutes'],0,$nows['mon'],$nows['mday'],$nows['year']);
    		$end	= mktime($hourMinute[0],$hourMinute[1],0,$dateEnd[1],$dateEnd[0],$dateEnd[2]);
    		
    		if($now > $end){
    			$this->exame->update(
    				array(
    					'exeKiemTra' => '0',
    					'status'	=>	'0'
    				), 
    				'idKiemTra ='.$_GET['id']
    			);
//    			$this->jShowMessage("Bài kiểm tra đã hết thời gian cho phép làm!!! Hãy gia hạn thời gian để có thể tiếp tục");
    			$this->jDialogMessage('Thông báo', 'Bài kiểm tra đã hết thời gian cho phép làm!!! Hãy gia hạn thời gian để có thể tiếp tục');
    		}else{
    			$this->exame->update(
    				array(
    					'exeKiemTra' => '1',
    					'status'	=>	'1'
    				), 
    				'idKiemTra ='.$_GET['id']
    			);
//				$this->jShowMessage("Đã kích hoạt để làm bài kiểm tra");
				$this->jDialogMessage("Thông báo", "Đã kích hoạt để sinh viên có thể làm bài kiểm tra!!!");
    		}
    	}
    	$this->_forward('index','quiz','admin');
    }

    /**
     * 
     * refresh lai session
     * @param unknown_type $nameSession
     */
    private function refreshSession($nameSession="quizSession"){
    	$this->quizSessionGet = Zend_Session::namespaceGet($nameSession);
    }
    
}









